package com.lixw.langchain.controller;

import com.lixw.langchain.service.McpService;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: McpCallServerController
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/8/26 18:16
 **/
@RestController
public class McpCallServerController {
    @Autowired
    private StreamingChatModel streamingChatModel;

    @GetMapping("/mcp/chat")
    public Flux<String> chat(@RequestParam("question") String question) {
        //构建McpTransport协议 - 使用本地标准输入输出io通信 需要保证MCP客户端和服务端必须在同一台机器上
        StdioMcpTransport mcpTransport = new StdioMcpTransport.Builder()
                .command(List.of("cmd", "/c", "npx", "-y", "@baidumap/mcp-server-baidu-map"))
                .environment(Map.of("BAIDU_MAP_API_KEY", System.getenv("BAIDU_API_KEY")))
                .build();

        DefaultMcpClient mcpClient = new DefaultMcpClient.Builder()
                .key("baidu_map_mcp_server")
                .transport(mcpTransport)
                .build();

        McpToolProvider mcpToolProvider = McpToolProvider.builder()
                .mcpClients(mcpClient)
                .build();

        McpService mcpService = AiServices.builder(McpService.class)
                .streamingChatModel(streamingChatModel)
                .toolProvider(mcpToolProvider)
                .build();

        return mcpService.chat(question);
    }
}